include ../../config.mk

TARG   := $(notdir $(abspath $(dir $(firstword $(MAKEFILE_LIST)))))
OFILES += ${TARG}.o
HFILES += ../getopt_helper.h ../version.h ../metaargs_helper.h ../metaargs.h

SUPPORTED_COMPILERS := gcc clang tcc

src_files = $(wildcard ./*.c ./*.h)


.PHONY: all
all: ${TARG} ${SYM}


.PHONY: clang-tidy-check
clang-tidy-check: ${TARG}.c
	${CLANG_TIDY} --quiet --warnings-as-errors='*' ${src_files}


.PHONY: clang-format-check
clang-format-check:
	${CLANG_FORMAT} --dry-run -Werror ${src_files}


define test_compiler

	make clean
	make CC='${1}' all
endef
.PHONY: test_compilers
test_compilers:
	$(foreach _,${SUPPORTED_COMPILERS},$(call test_compiler,${_}))
	make clean


.PHONY: check-all
check-all: test_compilers clang-tidy-check clang-format-check

../getopt_helper.h: ../version.h

${OFILES}: ${HFILES} ${METALANG99INC}

${TARG}.o: CPPFLAGS += -DPROG_NAME='"${@:.o=}"'
.c.o:
	$(CC) ${CFLAGS} ${CPPFLAGS} -c ${<} -o ${@}

${TARG}: ${OFILES}
	$(CC) ${CFLAGS} ${LDFLAGS} ${^} -o ${@}


install: ${TARG} ${SYM}
	install -Dm755 -- ${TARG} ${DESTDIR}${PREFIX}/bin/${TARG}
ifneq (,${SYM})
	for s in ${SYM}; do cp -fd -- "$$s" ${DESTDIR}${PREFIX}/bin/; done
endif


${DESTDIR}${PREFIX}/bin:
	mkdir -p -- ${@}


ifneq (,${SYM})
${SYM}: ${TARG}
	ln -s -- ${<} ${@}
endif


.PHONY: uninstall
uninstall:
	rm -f -- ${DESTDIR}${PREFIX}/bin/${TARG}
ifneq (,${SYM})
	rm -f -- $(addprefix ${DESTDIR}${PREFIX}/bin/,${SYM})
endif

.PHONY: clean
clean:
	rm -f -- ${TARG} ${OFILES} ${SYM}
